<?php
/**
 *
 * PHP API 商品扩展控制器
 * @author jeff liu
 * powered by jeff liu
 */
class GoodsstatisticsApp extends ApiApp
{

    function __construct()
    {
        $this->GoodsstatisticsApp();
    }

    function GoodsstatisticsApp()
    {
        parent::__construct();
        $this->_goodsstatistics_mod =& api_model('goodsstatistics');
        $this->_goods_mod =& api_model('goods');
    }

    /**
     * 取得商品的热度
     *
     */
    function apiGetGoodsHits()
    {
        $goods_ids = $this->_get_goods_ids();
        //交易记录中买家已付款即可
        $sql = sprintf(
            'SELECT goods_id,views
                        FROM %s 
                        WHERE goods_id in(%s)',
            $this->_goodsstatistics_mod->table,
            implode(',', $goods_ids)
        );
        $data = $this->_goodsstatistics_mod->getAll($sql);
        $this->echo_result($data);
    }

    /**
     * 更新商品热度
     */
    function apiAddGoodsHitsByOne()
    {
        $goods_ids = $this->_get_goods_ids();

        $data = array();
        //参数检查
        if (empty($goods_ids)) {
            $data = array(0 => -1);
        } else {
            foreach ((array)$goods_ids as $goods_id) {
                $g_info = $this->_goodsstatistics_mod->get($goods_id);

                /* 更新浏览次数 */
                $this->_goodsstatistics_mod->edit($goods_id, 'views = views + 1');

                if (!empty($g_info)) {
                    $data[$goods_id] = $g_info['views'] + 1;
                } else {
                    $data[$goods_id] = 1;
                }
            }
        }

        $this->echo_result($data);
    }

    /**
     *
     * 根据商品类型获取此类型的所有商品关注度
     */
    function apiGetGoodsViewsByType()
    {
        if (!isset($_REQUEST['type']) && !isset($_REQUEST['store_ids'])) {
            return;
        }

        $sql_a = ' WHERE 1 AND 1 ';

        if (!empty($_REQUEST['type'])) {
            $type = $_REQUEST['type'];

            $sql_a = $sql_a . " AND g.type = '" . $type . "'";
        }

        if (!empty($_REQUEST['store_ids'])) {
            $store_ids = $_REQUEST['store_ids'];

            $sql_a = $sql_a . " AND g.store_id in (" . $store_ids . ")";
        }

        $sql = "SELECT SUM(gs.`views`) as total_views FROM " . $this->_goodsstatistics_mod->table . " gs LEFT JOIN " . $this->_goods_mod->table . "  g ON gs.`goods_id` = g.`goods_id` " . $sql_a;
        $data = $this->_goodsstatistics_mod->getAll($sql);
        $data = current($data);
        $this->echo_result($data);

    }

}